//
//  FenLeiViewController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/7/27.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "FenLeiViewController.h"

#import "ClassSearchHomeVIew.h"//搜索条

#import "CollectionViewHeaderView.h"
#import "CollectionViewCell.h"

#import "fenLeiDetailViewController.h"//商品详情

#import "FenLeiModle.h"
#import "FenLeiTwoModle.h"
#import "FenLeiThreeModle.h"


#define CellIdentifier @"CellIdentifier"
#define tableViewCellIdentifier @"UITableViewCell"

@interface FenLeiViewController ()<UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,ClassSearchHomeViewdelegate>
{
    //搜索条
    ClassSearchHomeVIew *searchView;
    
    BOOL flage;
    
}
@property (nonatomic,strong) UITableView * leftTableView;
@property (nonatomic,strong) UICollectionView * rightCollectionView;

@property (nonatomic,assign) NSInteger  selectIndex;//点击tableview.row
@property (nonatomic,assign) BOOL  isScrollDown;
@property (nonatomic,strong) UIView * lineView1;//tableview右侧分割线
@property (nonatomic,strong) UIView * lineView2;//tableview右侧分割线

@property (nonatomic,strong) UICollectionViewFlowLayout * flowLayout;
@property (nonatomic,strong) NSArray * dataSource;

@property (nonatomic, strong) NSMutableArray *dataArr;
@end

@implementation FenLeiViewController

-(UITableView *)leftTableView{
    
    if (!_leftTableView) {
        _leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 70, self.view.bounds.size.width*0.3-2, self.view.bounds.size.height-64-70) style:UITableViewStylePlain];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.separatorStyle = UITableViewRowAnimationNone;
        [_leftTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:tableViewCellIdentifier];
        _leftTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
        
    }
    return _leftTableView;
}

-(UIView *)lineView1{
    
    if (!_lineView1) {
        _lineView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, 0.5)];
        _lineView1.backgroundColor =BaseColor;
    }
    return _lineView1;
}
-(UIView *)lineView2{
    
    if (!_lineView2) {
        _lineView2 = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.leftTableView.frame)+0.5, 64, 0.5, self.view.bounds.size.height-64)];
        _lineView2.backgroundColor = BaseColor;
    }
    return _lineView2;
}

-(UICollectionView *)rightCollectionView{
    
    if (!_rightCollectionView) {
        
        self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
        _rightCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width*0.3, 70, self.view.bounds.size.width*0.7, self.view.bounds.size.height-64-70) collectionViewLayout:self.flowLayout];
        self.flowLayout.minimumLineSpacing = 10;
        self.flowLayout.minimumInteritemSpacing = 10;
        
        self.flowLayout.itemSize = CGSizeMake((self.rightCollectionView.bounds.size.width-41)/3, (self.rightCollectionView.bounds.size.height-30)/5.5);
        self.flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        self.flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
        _rightCollectionView.delegate = self;
        _rightCollectionView.dataSource = self;
        
        [_rightCollectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:CellIdentifier];
        _rightCollectionView.backgroundColor = [UIColor whiteColor];
        
        [_rightCollectionView registerClass:[CollectionViewHeaderView class]
                 forSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                        withReuseIdentifier:@"CollectionViewHeaderView"];
        
    }
    return _rightCollectionView;
}
#pragma mark ---------------- 获取数据 ------------------
//http://bs.m0571.com/mobileapi/public/baishi/?service=Shop_Category.GetCategoryList&userid=11actoken=1bc99c0bb52371e5ec7cdb9230515dd9.900.1504692352

-(void)getData{
    
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};

    [HttpRequest postWithURLString:POST(Shop_GetCategoryList) parameters:parameDic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        if ([[responseObject objectForKey:@"ret"] integerValue] == 200) {
            
            _dataArr = [FenLeiModle mj_objectArrayWithKeyValuesArray:[[responseObject objectForKey:@"data"] objectForKey:@"info"]];
            
//            FenLeiModle *model = _dataArr[0];
//            FenLeiTwoModle *modle2 = model.down[0];
//            FenLeiThreeModle *modle3 = modle2.down[0];
//            NSString *name = modle3.name;
            [self.leftTableView reloadData];
            [self.rightCollectionView reloadData];
     
            NSIndexPath *selIndex = [NSIndexPath indexPathForRow:0 inSection:0];
            [_leftTableView selectRowAtIndexPath:selIndex animated:YES scrollPosition:UITableViewScrollPositionTop];
            NSIndexPath * path = [NSIndexPath indexPathForItem:0 inSection:0];
            [self tableView:self.leftTableView didSelectRowAtIndexPath:path];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.fd_prefersNavigationBarHidden = YES;
    
    _dataArr = [NSMutableArray array];
    
    [self addNavUI];
    
    
    
    
    
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.lineView1];
    [self.view addSubview:self.lineView2];
    [self.view addSubview:self.rightCollectionView];
    
    [self getData];
    

}

#pragma  mark --------------- NAV ----------
-(void)addNavUI{
    searchView  = [[ClassSearchHomeVIew alloc] initWithFrame:CGRectMake(0, 20, kScreen_Width, 64-20)];
    searchView.backgroundColor = [UIColor clearColor];
    searchView.delegate = self;
    searchView.userInteractionEnabled = YES;
    [self.view addSubview:searchView];
    
    
}

-(void)middlebuttonclcik{
    NSLog(@"middlebuttonclcik");
}
-(void)rightButtonclcik{
    NSLog(@"rightButtonclcik");
    
}

#pragma mark UITableView
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArr.count;
//    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableViewCellIdentifier forIndexPath:indexPath];
    UIView *bview = [[UIView alloc]initWithFrame:cell.frame];

    cell.selectedBackgroundView = bview;
    cell.selectedTextColor = [UIColor whiteColor];


//    cell.selectedBackgroundView = bview;
//    cell.selectedTextColor = [UIColor whiteColor];
    
    if (_selectIndex == indexPath.row) {
        cell.backgroundView = bview;
        cell.textLabel.textColor = [UIColor whiteColor];
    }else{
        cell.backgroundView = nil;
        cell.textLabel.textColor = [UIColor blackColor];
    }
    

    UIImageView *imgview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, self.view.bounds.size.width*0.3-20, 50-20)];
    imgview.image = [UIImage imageNamed:@"fenlei_kuai"];
    [bview addSubview:imgview];
    
    
    FenLeiModle *model = _dataArr[indexPath.row];
    cell.textLabel.text = model.name;
    
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.font = [UIFont systemFontOfSize:15.0];
    cell.textLabel.backgroundColor = [UIColor clearColor];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    self.selectIndex = indexPath.row;

    [self scrollToTopOfSection:self.selectIndex animated:YES];
    [self.leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.selectIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
    self.selectIndex = indexPath.row;
    [self.leftTableView reloadData];
    
}

- (void)scrollToTopOfSection:(NSInteger)section animated:(BOOL)animated{
    
    FenLeiModle *model = _dataArr[section];
    
    if (model.down.count) {
        CGRect headerRect = [self frameForHeaderForSection:section];
        CGPoint topOfHeader = CGPointMake(0, headerRect.origin.y-self.rightCollectionView.contentInset.top);
        [self.rightCollectionView setContentOffset:topOfHeader animated:animated];
    }else{
        //[MBProgressHUD showText:@"哈哈"];
    }

}

-(CGRect)frameForHeaderForSection:(NSInteger)section{
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:section];
    UICollectionViewLayoutAttributes *attributes = [self.rightCollectionView layoutAttributesForItemAtIndexPath:indexPath];
    CGRect frameForFirstCell = attributes.frame;
    CGFloat headerHeight = [self collectionView:self.rightCollectionView layout:self.flowLayout referenceSizeForHeaderInSection:section].height;
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)self.rightCollectionView.collectionViewLayout;
    CGFloat cellTopEdge = flowLayout.sectionInset.top;
    return CGRectOffset(frameForFirstCell, 0, -headerHeight-cellTopEdge);
    
    
}


#pragma mark UICollectionView
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    
    return self.dataArr.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    FenLeiModle *model = _dataArr[section];

    return model.down.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    FenLeiModle *model = _dataArr[indexPath.section];
    FenLeiTwoModle *modle2 = model.down[0];
    FenLeiThreeModle *modle3 = modle2.down[indexPath.row];
    
    cell.name.text = modle3.name;
    
    cell.imgView.image =[UIImage imageNamed:@"quetu"];
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    NSString *reuseIdentifier;
    // header
    if ([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        reuseIdentifier = @"CollectionViewHeaderView";
    }
    CollectionViewHeaderView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        FenLeiModle *model = _dataArr[indexPath.section];
        view.label.text = model.name;
    }
    return view;
    
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(self.rightCollectionView.frame.size.width, 30);
}

-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (!self.isScrollDown && collectionView.dragging) {
        [self selectRowAtIndexPath:indexPath.section];
    }
}


-(void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isScrollDown && collectionView.dragging) {
        [self selectRowAtIndexPath:indexPath.section];
    }
}


-(void)selectRowAtIndexPath:(NSInteger)index{
    
    [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            NSLog(@"别摸我");
        }
    }
    
    FenLeiModle *model = _dataArr[indexPath.section];
    FenLeiTwoModle *modle2 = model.down[0];
    FenLeiThreeModle *modle3 = modle2.down[indexPath.row];
    fenLeiDetailViewController *vc = [[fenLeiDetailViewController alloc] init];
    vc.cat_id = modle3.Id;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES
     ];
    NSLog(@"%ld分组 %ld单元格",indexPath.section,indexPath.row);
}




#pragma mark - UIScrollView Delegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    static float lastOffSetY = 0;
    if (self.rightCollectionView == scrollView) {
        self.isScrollDown = lastOffSetY < scrollView.contentOffset.y;
        lastOffSetY = scrollView.contentOffset.y;
    }
}


-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];

    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    self.navigationController.navigationBarHidden = YES;

  self.navigationController.navigationBarHidden = YES;
    
    
    
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    self.navigationController.navigationBarHidden = NO;


}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}




@end
